package com.toprs.base.service

import com.toprs.base.annotation.PageQuery
import com.toprs.base.config.RequestHolder
import com.toprs.base.entity.Log
import com.toprs.base.entity.User
import com.toprs.base.entity.UserBase
import com.toprs.base.entity.UserDept
//import com.toprs.base.entity.UserRole
import com.toprs.base.vo.UpdatePasswordVO
import com.toprs.base.exception.CustomException
import com.toprs.base.mapper.*
import com.toprs.base.mapper.DeptManagerDynamicSqlSupport.deptId
import com.toprs.base.mapper.UserDynamicSqlSupport.phone
import com.toprs.base.mapper.UserDynamicSqlSupport.userid
import com.toprs.base.mapper.UserDynamicSqlSupport.password
import com.toprs.base.mapper.UserDynamicSqlSupport.realname
import com.toprs.base.query.UserQuery
import com.toprs.base.result.PageResult
import com.toprs.base.vo.UserVO
import jakarta.servlet.http.HttpServletRequest
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service

@Service
class UserService(
    val userDeptMapper: UserDeptMapper,
    val userMapper: UserMapper,
    val deptManagerMapper: DeptManagerMapper,
    val logMapper: LogMapper
) {

    private val keySecret = "MIICdgIBADANBgkqhkiG92osde5PIROeLEZ+uZYNI+HeLKjPXUpB/3DcmQX7FMvJ/"
    private val encoder by lazy {
        BCryptPasswordEncoder()
    }

    fun addUser(user: User) {
        val userSelect = userMapper.selectOne { where { phone.isEqualTo(user.phone as String) } }
        if (userSelect != null) {
            throw CustomException(500, "该手机号已注册")
        }

        val password = encoder.encode(user.password + keySecret)
        user.password = password

        if (user.deptIds == null || user.deptIds!!.isEmpty()) throw CustomException("请选择部门！")

        user.userid = "0s1${user.deptIds!![0]}${System.currentTimeMillis()}"
        user.active = 1
        userMapper.insert(user)

        for (id in user.deptIds!!) {
            userDeptMapper.insert(UserDept(user.userid, id))
        }

    }

    fun deleteUser(id: String) {
        val user = userMapper.selectByPrimaryKey(id)

        if (user != null && user.admin == 1.toShort()) {
            throw CustomException("无法删除管理员账户！")
        }
        userMapper.deleteByPrimaryKey(id)
    }


    fun login(userVO: UserVO, httpServletRequest: HttpServletRequest): User {

        val user = userMapper.selectOneWithDeptName(userVO.phone)

        val log = Log()
        log.username = userVO.phone
        log.ip = httpServletRequest.remoteAddr
        if (user == null) {
            log.logContent = "${userVO.phone}=>!手机号不存在"
            logMapper.insertLogin(log)
            throw CustomException(500, "手机号未注册！")
        } else if (!encoder.matches(userVO.password + keySecret, user.password)) {
            log.logContent = "${userVO.phone}=>!密码错误"
            logMapper.insertLogin(log)
            throw CustomException(500, "密码错误！")
        } else {
            val ids = userDeptMapper.selectByUserId(user.userid)
            user.deptIds = ids
            log.logContent = "${user.realname}==>登录成功"
            logMapper.insertLogin(log)
            return user
        }
    }

    fun logOut(id: String, httpServletRequest: HttpServletRequest) {
        val user = userMapper.selectByPrimaryKey(id) ?: throw CustomException(500, "退出登录失败！")
        val log = Log()
        log.username = user.realname
        log.ip = httpServletRequest.remoteAddr
        log.logContent = "${user.realname}<==退出登录"
        logMapper.insertLogin(log)
    }


    @PageQuery
    fun queryUser(query: UserQuery): PageResult<UserBase> {
        val list = userMapper.queryUser(query)
        val pageResult = PageResult.processPage(list)
        val manager = deptManagerMapper.select {
            where {
                deptId.isEqualTo(query.deptId!!)
            }
        }
        if (pageResult.list?.isNotEmpty() == true)
            pageResult.list?.map {
                it.manager = it.userid == if (manager.isEmpty()) "" else (manager[0].userid ?: "")
            }
        return pageResult
    }

    fun editUser(user: User) {
        if (user.userid == null) {
            throw CustomException("用户id不能为空！")
        }

        userDeptMapper.deleteByUserid(user.userid!!)
        for (id in user.deptIds!!) {
            userDeptMapper.insert(UserDept(user.userid, id))
        }
        userMapper.updateByPrimaryKey(user)
    }

    fun getIsManager(user: User): Boolean {
        return if (user.deptIds!!.isEmpty())
            false
        else
            deptManagerMapper.selectselectBydeptIds(user.deptIds!!).any {
                it.userid.equals(user.userid)
            }
    }

    fun getUserInfo(userid: String): User? {

        val user = userMapper.selectByPrimaryKey(userid) ?: throw CustomException("用户不存在！")

        user.deptIds = userDeptMapper.selectByUserId(user.userid)
        user.manager = getIsManager(user)

        return user
    }

    fun updateSelf(user: User) {
        println(RequestHolder.getUserId())

        if (RequestHolder.getUserId() != user.userid) {
            throw CustomException("不能更新其他用户信息！")
        }
        if (user.userid == null) {
            throw CustomException("用户id不能为空")
        }
        userMapper.updateSelf(user, RequestHolder.getUserId())
    }

    fun getUserInfoSelf(): User {
        val id = RequestHolder.getUserId()

        val user = userMapper.selectByPrimaryKey(id) ?: throw CustomException("该用户已删除请重新登录！")

        user.deptIds = userDeptMapper.selectByUserId(id)

        return user
    }

    fun checkPassOld(old: String) {
        val id1 = RequestHolder.getUserId()
        val user =
            userMapper.selectOne { where { userid isEqualTo id1 } } ?: throw CustomException(500, "系统错误！")
        if (!encoder.matches(old + keySecret, user.password)) {
            throw CustomException(500, "原密码错误！")
        }

    }

    fun updatePassword(updatePassEntity: UpdatePasswordVO) {
        val id1 = RequestHolder.getUserId()
        val user = userMapper.selectOne { where { userid isEqualTo id1 } } ?: throw CustomException(500, "系统错误！")
        if (!encoder.matches(updatePassEntity.password0 + keySecret, user.password)) {
            throw CustomException(500, "原密码错误！")
        }
        if (updatePassEntity.password2 != updatePassEntity.password3) {
            throw CustomException(500, "两次密码不一致！")
        }
        userMapper.update {
            set(password).equalToOrNull(encoder.encode(updatePassEntity.password2 + keySecret))
            where {
                userid.isEqualTo(id1)
            }
        }
    }

    fun resetUserPassword(id: String): String {

        val userId = RequestHolder.getUserId()

        val user = userMapper.selectByPrimaryKey(userId)!!

        if (user.admin != 1.toShort()) throw CustomException("您没有初始化密码的权限！")
        val password = encoder.encode("a*2024$keySecret")
        userMapper.update {
            set(UserDynamicSqlSupport.password).equalToOrNull(password)
            where {
                userid.isEqualTo(id)
            }
        }
        return "a*2024"
    }

    fun getAllList(realname_: String): List<UserBase> {
        return userMapper.select {
            where {
                realname.isLike("%$realname_%")
            }
        }
    }


}